package com.szgd.controller.schedule;

import com.szgd.bean.SysDict;
import com.szgd.controller.BaseController;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.schedule.MainWorkScheduleService;
import com.szgd.service.schedule.SegmentProduceScheduleService;
import com.szgd.util.PropertiesUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/mainWorkSchedule")
public class MainWorkScheduleController extends BaseController {
    private static Logger logger = Logger.getLogger(MainWorkScheduleController.class);
    @Autowired
    AttachService attachService;
    @Autowired
    MainWorkScheduleService mainWorkScheduleService;
    @Autowired
    SegmentProduceScheduleService segmentProduceScheduleService;

    @RequestMapping(value = "/toSite", method = RequestMethod.GET)
    public ModelAndView toSite(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/site");
        Map<String,Object> param = new HashMap<>();
        param.put("source",0);
        List<Map<String,Object>> dateList = mainWorkScheduleService.getTime(param);
        mv.addObject("dateList", dateList);
        return mv;
    }

    @RequestMapping(value = "/toSection", method = RequestMethod.GET)
    public ModelAndView toSection(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/section");
        Map<String,Object> param = new HashMap<>();
        param.put("source",1);
        List<Map<String,Object>> dateList = mainWorkScheduleService.getTime(param);
        mv.addObject("dateList", dateList);
        return mv;
    }

    @RequestMapping(value = "/toSegment", method = RequestMethod.GET)
    public ModelAndView toSegment(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/segment");
        List<Map<String,Object>> dateList = segmentProduceScheduleService.getTime(null);
        mv.addObject("dateList", dateList);
        return mv;
    }

    @RequestMapping(value = "/toWHJG", method = RequestMethod.GET)
    public ModelAndView toWHJG(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/subMain");
        List<Map<String,Object>> dateList = mainWorkScheduleService.getTime(null);
        mv.addObject("dateList", dateList);
        mv.addObject("flag", "whjg");
        return mv;
    }

    @RequestMapping(value = "/toTFKW", method = RequestMethod.GET)
    public ModelAndView toTFKW(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/subMain");
        List<Map<String,Object>> dateList = mainWorkScheduleService.getTime(null);
        mv.addObject("dateList", dateList);
        mv.addObject("flag", "tfkw");
        return mv;
    }

    @RequestMapping(value = "/toZTJG", method = RequestMethod.GET)
    public ModelAndView toZTJG(HttpServletRequest request, HttpSession httpSession) {
        ModelAndView mv = this.getModelAndView(request,httpSession,"/schedule/mainSchedule/subMain");
        List<Map<String,Object>> dateList = mainWorkScheduleService.getTime(null);
        mv.addObject("dateList", dateList);
        mv.addObject("flag", "ztjg");
        return mv;
    }

    @RequestMapping(value = "/getChart")
    @ResponseBody
    public Map<String,Object> getChart(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.getChart(paramMap);
    }

    @RequestMapping(value = "/getChart2")
    @ResponseBody
    public Map<String,Object> getChart2(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.getChart2(paramMap);
    }

    @RequestMapping(value = "/getChartBySite2")
    @ResponseBody
    public Map<String,Object> getChartBySite2(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.getChartBySite2(paramMap);
    }

    @RequestMapping(value = "/getSegmentChart")
    @ResponseBody
    public Map<String,Object> getSegmentChart(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return segmentProduceScheduleService.getChart(paramMap);
    }

    @RequestMapping(value = "/getSegmentChartTable")
    @ResponseBody
    public Map<String,Object> getSegmentChartTable(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return segmentProduceScheduleService.getChartTable(paramMap);
    }

    @RequestMapping(value = "/getSiteTable")
    @ResponseBody
    public List<List<Map<String,Object>>> getSiteTable(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.getSiteTable(paramMap);
    }

    @RequestMapping(value = "/getSectionTable")
    @ResponseBody
    public List<List<Map<String,Object>>> getSectionTable(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.getSectionTable(paramMap);
    }


    @RequestMapping(value = "/uploadSiteMainWorkSchedule", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadSiteMainWorkSchedule(@RequestParam("file") MultipartFile[] updateFiles, HttpSession httpSession) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            InputStream is = updateFiles[0].getInputStream();
            String fileName = updateFiles[0].getOriginalFilename();
            int beginindex = fileName.indexOf("（");
            if (beginindex == -1)
                beginindex = fileName.indexOf("(");
            int endindex = fileName.indexOf("）");
            if (endindex == -1)
                endindex = fileName.indexOf(")");
            String dateStr  = "";
            if (beginindex > 0 && endindex > beginindex)
            {
                dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                if (dateStr.length() != 10)
                    return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }else
            {
                return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }

            ArrayList<SysDict> siteProjectNameList = (ArrayList<SysDict>)httpSession.getAttribute("SITE_PROJECT_NAME");
            boolean b = mainWorkScheduleService.importSiteMainWorkSchedule(updateFiles,this.getLoginId(httpSession),siteProjectNameList);
            if (b)
                return getSuccMap("导入成功");
            else
                return getErrorMap("导入失败,请检查格式是否正确！");
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("文件上传失败！-------"+e.getMessage());
        }
    }

    @RequestMapping(value = "/isHavaSiteMainWorkSchedule", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> isHavaSiteMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) {
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int weekNo = cal.get(Calendar.WEEK_OF_MONTH);
            int monthNo = cal.get(Calendar.MONTH) + 1;

            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime", weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime", weeklast);
            paramMap.put("source",0);
            List<Map<String, Object>> tempList = mainWorkScheduleService.getMainWorkScheduleList(paramMap);
            if (tempList == null || tempList.size() == 0) {
                return getErrorMap(monthNo+"月份第"+weekNo+"周没有进度数据");
            } else
                return getSuccMap("有数据");

        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("查询失败！-------" + e.getMessage());
        }
    }

    @RequestMapping(value = "/downloadSiteMainWorkSchedule")
    public void downloadSiteMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime",weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime",weeklast);
            paramMap.put("source",0);
            List<Map<String,Object>> tempList = mainWorkScheduleService.getMainWorkScheduleList(paramMap);
            if (tempList != null && tempList.size() > 0)
            {
                String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
                if (attachId != null)
                {
                    Map<String, Object> attachMap = attachService.getAttach(attachId);
                    String fullPath = fileUploadPath + File.separator + attachMap.get("path")+ File.separator +  attachMap.get("name");
                    try {
                        this.download(response, fullPath);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/uploadSectionMainWorkSchedule", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadSectionMainWorkSchedule(@RequestParam("file") MultipartFile[] updateFiles, HttpSession httpSession) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            InputStream is = updateFiles[0].getInputStream();
            String fileName = updateFiles[0].getOriginalFilename();

            int beginindex = fileName.indexOf("（");
            if (beginindex == -1)
                beginindex = fileName.indexOf("(");
            int endindex = fileName.indexOf("）");
            if (endindex == -1)
                endindex = fileName.indexOf(")");
            String dateStr  = "";
            if (beginindex > 0 && endindex > beginindex)
            {
                dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                if (dateStr.length() != 10)
                    return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }else
            {
                return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }
            ArrayList<SysDict> siteProjectNameList = (ArrayList<SysDict>)httpSession.getAttribute("SITE_PROJECT_NAME");
            boolean b = mainWorkScheduleService.importSectionMainWorkSchedule(updateFiles,this.getLoginId(httpSession),siteProjectNameList);
            if (b)
                return getSuccMap("导入成功");
            else
                return getErrorMap("导入失败,请检查格式是否正确！");
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("文件上传失败！-------"+e.getMessage());
        }
    }


    @RequestMapping(value = "/isHavaSectionMainWorkSchedule", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> isHavaSectionMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) {
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int weekNo = cal.get(Calendar.WEEK_OF_MONTH);
            int monthNo = cal.get(Calendar.MONTH) + 1;
            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime", weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime", weeklast);
            paramMap.put("source",1);
            List<Map<String, Object>> tempList = mainWorkScheduleService.getMainWorkScheduleList(paramMap);
            if (tempList == null || tempList.size() == 0) {
                return getErrorMap(monthNo+"月份第"+weekNo+"周没有进度数据");
            } else
                return getSuccMap("有数据");

        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("查询失败！-------" + e.getMessage());
        }
    }

    @RequestMapping(value = "/downloadSectionMainWorkSchedule")
    public void downloadSectionMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime",weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime",weeklast);
            paramMap.put("source",1);
            List<Map<String,Object>> tempList = mainWorkScheduleService.getMainWorkScheduleList(paramMap);
            if (tempList != null && tempList.size() > 0)
            {
                String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
                if (attachId != null)
                {
                    Map<String, Object> attachMap = attachService.getAttach(attachId);
                    String fullPath = fileUploadPath + File.separator + attachMap.get("path")+ File.separator +  attachMap.get("name");
                    try {
                        this.download(response, fullPath);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/uploadSegmentMainWorkSchedule", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> uploadSegmentMainWorkSchedule(@RequestParam("file") MultipartFile[] updateFiles, HttpSession httpSession) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            List<String> uploadFileNameList = new ArrayList<String>();
            InputStream is = updateFiles[0].getInputStream();
            String fileName = updateFiles[0].getOriginalFilename();
            int beginindex = fileName.indexOf("（");
            if (beginindex == -1)
                beginindex = fileName.indexOf("(");
            int endindex = fileName.indexOf("）");
            if (endindex == -1)
                endindex = fileName.indexOf(")");
            String dateStr  = "";
            if (beginindex > 0 && endindex > beginindex)
            {
                dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                if (dateStr.length() != 10)
                    return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }else
            {
                return getErrorMap("文件名格式不对，没有含有日期或包含的日期格式不对，正确格式：XXX（YYYY.MM.DD）");
            }

            boolean b = segmentProduceScheduleService.importSegmentMainWorkSchedule(updateFiles,this.getLoginId(httpSession));
            if (b)
                return getSuccMap("导入成功");
            else
                return getErrorMap("导入失败,请检查格式是否正确！");
        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("文件上传失败！-------"+e.getMessage());
        }
    }

    @RequestMapping(value = "/isHavaSegmentMainWorkSchedule", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> isHavaSegmentMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) {
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int weekNo = cal.get(Calendar.WEEK_OF_MONTH);
            int monthNo = cal.get(Calendar.MONTH) + 1;
            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime", weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime", weeklast);
            List<Map<String, Object>> tempList = segmentProduceScheduleService.getSegmentProduceScheduleList(paramMap);
            if (tempList == null || tempList.size() == 0) {
                return getErrorMap(monthNo+"月份第"+weekNo+"周没有进度数据");
            } else
                return getSuccMap("有数据");

        } catch (Exception e) {
            e.printStackTrace();
            return getErrorMap("查询失败！-------" + e.getMessage());
        }
    }

    @RequestMapping(value = "/downloadSegmentMainWorkSchedule")
    public void downloadSegmentMainWorkSchedule(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileUploadPath = PropertiesUtil.get("uploadPath");
        String statisticsTime = getParam(request, "statisticsTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> paramMap = new HashMap<>();
        try {
            Date date = sdf.parse(statisticsTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            cal.set(cal.DAY_OF_WEEK, cal.MONDAY);
            String weekhand = sdf.format(cal.getTime());
            paramMap.put("startStatisticsTime",weekhand);
            cal.set(Calendar.DATE, cal.get(cal.DATE) + 6);
            String weeklast = sdf.format(cal.getTime());
            paramMap.put("endStatisticsTime",weeklast);
            List<Map<String,Object>> tempList = segmentProduceScheduleService.getSegmentProduceScheduleList(paramMap);
            if (tempList != null && tempList.size() > 0)
            {
                String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
                if (attachId != null)
                {
                    Map<String, Object> attachMap = attachService.getAttach(attachId);
                    String fullPath = fileUploadPath + File.separator + attachMap.get("path")+ File.separator +  attachMap.get("name");
                    try {
                        this.download(response, fullPath);
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/siteCompleteRateAvg")
    @ResponseBody
    public Double siteCompleteRateAvg(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.siteCompleteRateAvg(paramMap);
    }

    @RequestMapping(value = "/sectionCompleteRateAvg")
    @ResponseBody
    public Double sectionCompleteRateAvg(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.sectionCompleteRateAvg(paramMap);
    }

    @RequestMapping(value = "/segmentCompleteRateAvg")
    @ResponseBody
    public Double segmentCompleteRateAvg(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return segmentProduceScheduleService.segmentCompleteRateAvg(paramMap);
    }

    @RequestMapping(value = "/mainProjectCompleteRateAvg")
    @ResponseBody
    public Double mainProjectCompleteRateAvg(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        return mainWorkScheduleService.mainProjectCompleteRateAvg(paramMap);
    }
}
